package logic

import (
	"context"
	"edu-pro/models/cache"
	"edu-pro/models/mysql"
	"edu-pro/pkg"
	"errors"

	"edu-pro/edurpc/edurpc"
	"edu-pro/edurpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForgetPwdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForgetPwdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForgetPwdLogic {
	return &ForgetPwdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ForgetPwdLogic) ForgetPwd(in *edurpc.ForgetPwdRequest) (*edurpc.ForgetPwdResponse, error) {
	// 密码重置
	var user mysql.User
	mysql.DB.Debug().Where("phone = ?", in.Phone).Find(&user)
	if user.ID == 0 {
		return nil, errors.New("该号码还未注册，请您先注册")
	}
	smsCode, _ := cache.RDB.Get(l.ctx, "sendSms"+in.Phone).Result()
	if smsCode != in.SmsCode {
		return nil, errors.New("短信验证码有误，请重新输入")
	}
	if in.NewPassword1 != in.NewPassword2 {
		return nil, errors.New("两次密码输入不一致，请重新输入")
	}
	user.Password = pkg.Md5string(in.NewPassword1)
	mysql.DB.Debug().Model(&mysql.User{}).Where("id = ?", user.ID).Updates(&user)
	return &edurpc.ForgetPwdResponse{
		UserId: int64(user.ID),
	}, nil
}
